﻿package
{
	import flash.display.MovieClip;
	import flash.display.Stage;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display.StageDisplayState;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	import flash.events.ProgressEvent;
	import flash.events.FullScreenEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.ContextMenuEvent;
	import fl.events.ScrollEvent;
	import fl.controls.ComboBox;
	import fl.containers.ScrollPane;
	import fl.managers.StyleManager;
	import flash.text.TextField;
    import flash.text.TextFormat;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.net.FileReference;
	import flash.system.System;
	import flash.system.LoaderContext;
	import flash.utils.*;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	import flash.ui.ContextMenuBuiltInItems;
	import flash.ui.Keyboard;
	import flash.external.ExternalInterface;

	public class ComicPlayer extends MovieClip
	{
		private var myMenu:ContextMenu;
		private var myFSLabelFull:String = '全屏';
		private var myFSLabelNormal:String = '返回';
		private var myButtonSpace:int = 10; // 控制栏每个按钮之间的间距
		private var xmlPath:String = 'http://home.17dm.com/xml/';
		private var comicName:String = '';
		private var comicUrl:String = 'http://home.17dm.com/comic.php';
		private var comicId:int; // 漫画ID
		private var dirId:int; // 卷（话）ID
		private var dirIndex:int = 0; // 卷（话）索引
		private var dirNumber:int = 0; // 卷（话）数量
		private var dirPath:String; // 卷（话）列表路径
		private var dirListUrl:String; // 漫画列表URL
		private var picId:int; // 图片ID
		private var picIndex:int = 0; // 图片索引
		private var picNumber:int; // 图片数量
		private var picPath:String; // 图片列表路径
        private var OkBtn:SimpleButton;
		private var OkHander:Function = null;
        private var MsgBoxBg1:MovieClip;
        private var MsgBoxBg2:MovieClip;
        private var CancelBtn:SimpleButton;
        private var txt:TextField;
        private var msgTitle:TextField;
        private var t1:uint;
		private var imgLoader:Loader;
		private var imgSprite:Sprite;
		private var loadSize:int = 10; // 每次最多载入loadSize张漫画
		private var loadAll:Boolean = false;

		public function ComicPlayer()
		{
			// 控制舞台缩放比例
            stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.addEventListener(Event.RESIZE, onResizeDisplay);
			// 监听键盘事件
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardDown);
			// 监听全屏按钮单击事件
			myFullScreen.addEventListener(MouseEvent.CLICK, onMyFSClick);
			// 监听ScrollPane进程事件
			myScrollPane.addEventListener(ProgressEvent.PROGRESS, onScrollPaneProgress);
			// 监听ScrollPane完成事件
			myScrollPane.addEventListener(Event.COMPLETE, onScrollPaneComplete);
			// 设置全局风格
			setGlobalStyle();
			// 初始化提示框参数
			MessageBoxInit();
			// 设置全局XY坐标
			setGlobalXY();
			// 初始化参数
			initParams();
			// 上一页监听事件
			myPrevPic.addEventListener(MouseEvent.CLICK, onMyPrevPicClick);
			// 下一页监听事件
			myNextPic.addEventListener(MouseEvent.CLICK, onMyNextPicClick);
			// 分享监听事件
			myShare.addEventListener(MouseEvent.CLICK, onMyShareClick);
			// 收藏监听事件
			myFavorite.addEventListener(MouseEvent.CLICK, onMyFavoriteClick);
			// 图片列表监听事件
			myPicList.addEventListener(Event.CHANGE, onMyPicListChange);
			// 卷（话）列表监听事件
			myDirList.addEventListener(Event.CHANGE, onMyDirListChange);
			// 初始化外部接口
			initInterface();
			// 初始化右键菜单
			initContextMenu();
		}

		/**
		 * 初始化右键菜单
		 */
		private function initContextMenu():void
		{
            myMenu = new ContextMenu();
            myMenu.hideBuiltInItems();

			var item1:ContextMenuItem = new ContextMenuItem('查看图片');
			item1.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onSourcePic);
			myMenu.customItems.push(item1);

			var item2:ContextMenuItem = new ContextMenuItem('复制地址');
			item2.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onMyShareClick);
			myMenu.customItems.push(item2);
			/*
			var item3:ContextMenuItem = new ContextMenuItem('下载图片');
			item3.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onDownPic);
			myMenu.customItems.push(item3);
			*/
			var item10:ContextMenuItem = new ContextMenuItem('一起动漫');
			item10.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onHomePage);
			myMenu.customItems.push(item10);

            this.contextMenu = myMenu;
		}

		/**
		 * 查看原图
		 */
		private function onSourcePic(event:ContextMenuEvent):void
		{
			var imgurl = getPicUrl();
			if (imgurl == '') {
				MessageBoxShow('获取图片地址出错');
			} else {
				setStageNormal();
				gotoUrl(imgurl);
			}
		}

		private function onCopyPic(event:ContextMenuEvent):void
		{
			var imgurl = getPicUrl();
			if (imgurl == '') {
				MessageBoxShow('获取图片地址出错');
			} else {
				System.setClipboard(imgurl);
				MessageBoxShow('漫画地址复制成功\n您可以通过粘贴（Ctrl+V）推荐给QQ或MSN的好友');
			}
		}

		private function onDownPic(event:ContextMenuEvent):void
		{
			var imgurl = getPicUrl();
			if (imgurl == '') {
				MessageBoxShow('获取图片地址出错');
			} else {

				var file:FileReference = new FileReference();
				try {
					file.download(new URLRequest(imgurl));
				} catch(error:Error) {
					MessageBoxShow(error.message);
				}
				/*
				file.addEventListener(Event.CANCEL, cancelHandler);
				file.addEventListener(Event.COMPLETE, completeHandler);
				file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				file.addEventListener(Event.OPEN, openHandler);
				file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
				file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
				file.addEventListener(Event.SELECT, selectHandler);
				*/
			}
		}

		private function cancelHandler(event:Event):void
		{
			MessageBoxShow('cancelHandler');
		}

		private function progressHandler(event:ProgressEvent):void
		{
			MessageBoxShow('progressHandler');
		}

		private function selectHandler(event:Event):void
		{
			MessageBoxShow('selectHandler');
		}

		private function openHandler(event:Event):void
		{
			MessageBoxShow('打开时发生错误');
		}

		private function ioErrorHandler(event:IOErrorEvent):void
		{
			MessageBoxShow('下载时发生I/O读取错误');
		}

		private function securityErrorHandler(event:SecurityErrorEvent):void
		{
			MessageBoxShow('下载时发生安全错误');
		}

		private function completeHandler(event:Event):void
		{
			MessageBoxShow('下载完成');
		}

		/**
		 * 定位到首页
		 */
		private function onHomePage(event:ContextMenuEvent):void
		{
			setStageNormal();
			gotoUrl('http://www.17dm.com/');
		}

		private function initInterface():void
		{
			ExternalInterface.call('InitPlayer');
			ExternalInterface.addCallback('PrevPic', onMyPrevPicClick);
			ExternalInterface.addCallback('NextPic', onMyNextPicClick);
			ExternalInterface.addCallback('OnEnter', onEnter);
			ExternalInterface.addCallback('GoMoveByJS', GoMoveByJS);
		}

		private function GoMove(event:MouseEvent = null)
		{
			var vPosition = myScrollPane.verticalScrollPosition;

			if (event.delta > 0) { // 向上滚动
				vPosition = vPosition - 30;
			} else if (event.delta < 0) { // 向下滚动
				vPosition = vPosition + 30;
			}

			myScrollPane.verticalScrollPosition = vPosition; // 垂直滚动条
		}

		private function GoMoveByJS(param1:Number):void
		{
            var mouseEvent:MouseEvent = new MouseEvent(MouseEvent.MOUSE_WHEEL);
            mouseEvent.altKey = false;
            mouseEvent.delta  = param1;
            GoMove(mouseEvent);
		}

		private function onEnter():void
		{
			OkHander(); // 调用信息提示框的确定绑定函数
			MessageBoxClose();
		}

		private function onKeyboardDown(event:KeyboardEvent):void
		{
			trace(event.keyCode);

            var mouseEvent:MouseEvent = new MouseEvent(MouseEvent.MOUSE_WHEEL);
            mouseEvent.altKey = false;

			switch (event.keyCode) {
				case Keyboard.RIGHT:
					onMyNextPicClick(); // 下一页
					break;
				case Keyboard.LEFT:
					onMyPrevPicClick(); // 上一页
					break;
				case Keyboard.UP: // 向上滚动
					mouseEvent.delta = 1;
					GoMove(mouseEvent);
					break;
				case Keyboard.DOWN: // 向下滚动
					mouseEvent.delta = -1;
					GoMove(mouseEvent);
					break;
				case Keyboard.ENTER:
					OkHander(); // 调用信息提示框的确定绑定函数
					MessageBoxClose();
					break;
			}

			return;
		}

		private function onMyDirListChange(event:Event = null):void
		{
			myProgressBar.visible = true;

			dirIndex = myDirList.selectedIndex;
			myPicList.selectedIndex = 0;
			// 重新载入图片列表
			loadPicList();
		}

		private function onMyPicListChange(event:Event):void
		{
			picIndex = myPicList.selectedIndex;
			picId = getPicId();
			updateScrollPane();
		}

		private function onMyPrevPicClick(event:Event = null):void
		{
			myProgressBar.visible = true;
			MessageBox.visible = false;

			if (picIndex > 0) {
				picIndex--;
				myPicList.selectedIndex = picIndex;
				updateScrollPane();
			} else if (dirIndex >= dirNumber) { // 返回卷（话）列表
				MessageBoxShow('当前漫画已经全部浏览结束，是否返回列表页？', '提示信息', 0, gotoDirList);
			} else { // 定位上一卷（话）
				MessageBoxShow('已经是第一页 是否返回上一卷（话）？', '提示信息', 0, gotoPrevDir);
			}
		}

		private function onMyNextPicClick(event:Event = null):void
		{
			myProgressBar.visible = true;
			MessageBox.visible = false;

			if (picIndex < picNumber) {
				picIndex++;
				myPicList.selectedIndex = picIndex;
				updateScrollPane();
			} else if (dirIndex <= 0) { // 返回卷（话）列表
				MessageBoxShow('当前漫画已经全部浏览结束，是否返回列表页？', '提示信息', 0, gotoDirList);
			} else { // 定位上一卷（话）
				MessageBoxShow('已经是最后一页 是否继续浏览下一卷（话）？', '提示信息', 0, gotoNextDir);
			}
		}

		private function onMyShareClick(event:Event = null):void
		{
			var string:String =  comicName + ' ' + getDirName() + '\n' + getCurrentUrl();
			System.setClipboard(string);
			MessageBoxShow('漫画地址复制成功\n您可以通过粘贴（Ctrl+V）推荐给QQ或MSN的好友');
		}

		private function onMyFavoriteClick(event:Event):void
		{
			setStageNormal();
			ExternalInterface.call('addFavorites', comicName + ' ' + getDirName(), getCurrentUrl());
		}

		/**
		 * 定位到上一卷
		 */
		private function gotoPrevDir(event:MouseEvent = null):void
		{
			myDirList.selectedIndex = dirIndex + 1;
			onMyDirListChange();
		}

		/**
		 * 定位到下一卷
		 */
		private function gotoNextDir(event:MouseEvent = null):void
		{
			myDirList.selectedIndex = dirIndex - 1;
			onMyDirListChange();
		}

		/**
		 * 定位到卷列表
		 */
		private function gotoDirList(event:MouseEvent = null):void
		{
			setStageNormal();
			gotoUrl(dirListUrl, '_top');
		}

		/**
		 * 定位到指定的URL
		 */
		private function gotoUrl(toUrl:String, window:String = null):void
		{
            var request:URLRequest = new URLRequest(toUrl);
            try {
                navigateToURL(request, window);
            } catch (e:Error) {
				trace('跳转到'+toUrl+'失败');
                // handle error here
            }
		}

		/**
		 * 初始化参数
		 */
		private function initParams():void
		{
			var param:Object = root.loaderInfo.parameters;

			if (!isNaN(root.loaderInfo.parameters['comicid'])) {
				comicId = root.loaderInfo.parameters['comicid'];
			} else {
				MessageBoxShow('漫画ID无效');
			}

			// 漫画卷（话）列表
			dirPath = getDirPath();
			trace(dirPath);

            if (!isNaN(root.loaderInfo.parameters["dirid"])) {
                dirId = root.loaderInfo.parameters["dirid"];
            } else {
				dirId = 0;
				// MessageBoxShow('卷（话）ID无效');
            }

            if (!isNaN(root.loaderInfo.parameters["picid"])) {
                picId = root.loaderInfo.parameters["picid"];
            } else {
				picId = 0;
				// MessageBoxShow('图片ID无效');
			}

			// 漫画名字
			if (root.loaderInfo.parameters['comicname'] != null) {
				comicName = root.loaderInfo.parameters['comicname'];
			}

			// 页面地址
			if (root.loaderInfo.parameters['pageurl'] != null) {
				comicUrl = root.loaderInfo.parameters['pageurl'];
			}

			// 漫画列表地址
			if (root.loaderInfo.parameters['listurl'] != null) {
				dirListUrl = root.loaderInfo.parameters['listurl'];
			} else {
				dirListUrl = 'http://manhua.17dm.com/';
			}

			loadDirList();
		}

		/**
		 * 载入卷（话）列表
		 */
		private function loadDirList():void
		{
			var loadDir:URLLoader = new URLLoader(new URLRequest(dirPath));

			// 监听卷列表载入完成
			loadDir.addEventListener(Event.COMPLETE, onDirListLoadComplete);
			// 监听安全错误
			loadDir.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onDirXMLHttpError);
			// 监听I/0读取错误
			loadDir.addEventListener(IOErrorEvent.IO_ERROR, onDirXMLHttpError);
		}

		private function onDirListLoadComplete(event:Event):void
		{
			trace('卷（话）列表载入完成！');

			var maxLength:Number = 0;

			var dirData:XML = new XML(event.currentTarget.data);
			// comicName = dirData.attribute('comicname');
			if (dirData.Error.toString().length > 0) {
				trace(dirData.Error);
			} else {
				var i:int = 0;
				var dirName:String = '';
				for each (var list:XML in dirData.list) {
					dirName = strReplace(list.name, comicName, ''); // 替换多出来的漫画名字
					dirName = dirName.replace(/^\s*|\s*$/g,''); // 去掉空格
					myDirList.addItem({label:dirName, data:i, id:list.id});
					if (list.id == dirId) {
						myDirList.selectedIndex = i; // 选中的索引
						dirIndex = i;
					}
					i++;

				}
				// 卷（话）数量
				dirNumber = (i - 1);
				// 默认第一卷（话）选中
				if (myDirList.selectedIndex == -1) {
					myDirList.selectedIndex = 0;
					dirIndex = 0;
					dirId = getDirId();
				}
				for (i = 0; i < myDirList.length; i++) {
					myDirList.selectedIndex = i;
					myDirList.drawNow();
					var currWidth:Number = myDirList.textField.textWidth;
					maxLength = Math.max(currWidth, maxLength);
					// trace(currText, currWidth, maxLength);
				}

				myDirList.selectedIndex = dirIndex;
				myDirList.dropdownWidth = myDirList.width = maxLength + 30;
				myDirList.x  = myPicList.x - (myDirList.width + myButtonSpace); // 设置卷（话）列表按钮的X坐标
			}

			loadPicList();
		}

		/**
		 * 载入图片列表
		 */
		private function loadPicList()
		{
			// 漫画当前卷（话）图片列表
			picPath = getPicPath();
			trace(picPath);

			var loadPic:URLLoader = new URLLoader(new URLRequest(picPath));
			// 监听图片列表载入完成
			loadPic.addEventListener(Event.COMPLETE, onPicListLoadComplete);
			// 监听安全错误
			loadPic.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onPicXMLHttpError);
			// 监听I/O读取错误
			loadPic.addEventListener(IOErrorEvent.IO_ERROR, onPicXMLHttpError);
		}

		private function onPicListLoadComplete(event:Event):void
		{
			trace('图片列表载入完成！');

			var picData:XML = new XML(event.currentTarget.data);
			if (picData.Error.toString().length > 0) {
				trace(picData.Error);
			} else {
				var i:int = 0;
				var page:String = '';
				myPicList.removeAll(); // 先移除所有项目
				for each (var img:XML in picData.img) {
					page = '第'+(i+1)+'页';
					myPicList.addItem({label:page, data:img.url, id:img.id});
					if (img.id == picId) {
						myPicList.selectedIndex = i;
						picIndex = i;
					}
					i++;
				}
				// 图片数量
				picNumber = (i - 1);
				// 默认第一张图片选中
				if (myPicList.selectedIndex == -1) {
					myPicList.selectedIndex = 0;
					picIndex = 0;
					picId = getPicId();
				}
			}

			updateScrollPane();
		}

		private function loadAllImg():void
		{
			var i:int;
			var n:int = 0;
			var imgurl:String = '';
			for (i = picIndex; i < myPicList.length; i++) {
				// 开始载入下一张图片
				imgurl = getPicUrl(i);
				if (imgurl != '') {
					imgLoader = new Loader();
					imgLoader.load(new URLRequest(imgurl));
					imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImgLoaderComplete);
				}
				if (n >= loadSize) {
					break;
				}
				loadAll = true;
				n++;
			}
		}

		private function onImgLoaderComplete(event:Event):void
		{
			imgSprite = new Sprite();
			imgSprite.addChild(event.target.data);
		}

		private function updateScrollPane():void
		{
			myProgressBar.visible = true;

			var imgurl = getPicUrl();
			if (imgurl == '') {
				MessageBoxShow('获取图片地址出错');
			} else {
				imgLoader = new Loader();
				imgLoader.load(new URLRequest(imgurl));
				imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImgLoader);
			}
		}

		private function onImgLoader(event:Event):void
		{
			imgSprite = new Sprite();
			imgSprite.addChild(imgLoader);
			myScrollPane.source = imgSprite;
			onScrollPaneComplete();
		}

		private function onScrollPaneProgress(event:ProgressEvent):void
		{
			myProgressBar.visible = true; // 进度条可见

			var bLoaded:int = event.bytesLoaded;
			var bTotal:int = event.bytesTotal;
			var pctLoaded:int = event.target.percentLoaded as int;

			trace("图片载入: " + bLoaded + " of " + bTotal + " bytes loaded (" + pctLoaded + "%)");
		}

		private function onScrollPaneComplete(event:Event = null):void
		{
			myProgressBar.visible = false; // 进度条不可见

			myScrollPane.update();

			if (myScrollPane.content.width < myScrollPane.width) {
				myScrollPane.content.x = (myScrollPane.width-myScrollPane.content.width)/2;
			}

			myScrollPane.horizontalScrollPosition = 0; // 水平滚动条
			myScrollPane.verticalScrollPosition   = 0; // 垂直滚动条

			trace("图片载入完成");
			if (loadAll == false || (picIndex%loadSize) == 0) {
				loadAllImg(); // 载入所有图片
			}
		}

		private function onPicXMLHttpError(event:Event):void
		{
			var msg:String;

			if (event.type == 'securityError') {
				msg = '载入图片列表时发生安全读取错误！';
			} else if (event.type == 'ioError') {
				msg = '载入图片列表时发生I/O读取错误！';
			} else {
				msg = '载入图片列表时发生未知错误！';
			}

			MessageBoxShow(msg);
		}

		private function onDirXMLHttpError(event:Event):void
		{
			var msg:String;

			if (event.type == 'securityError') {
				msg = '载入卷（话）列表时发生安全读取错误！';
			} else if (event.type == 'ioError') {
				msg = '载入卷（话）列表时发生I/O读取错误！';
			} else {
				msg = '载入卷（话）列表时发生未知错误！';
			}

			MessageBoxShow(msg);
		}

		private function onResizeDisplay(event:Event):void
		{
			setGlobalXY(); // 设置全局XY坐标
		}

		private function onMyFSClick(event:MouseEvent = null):void
		{
			if (root.stage.displayState == "fullScreen") {
				stage.displayState = StageDisplayState.NORMAL;
				myFullScreen.label = myFSLabelFull;
			} else {
				stage.displayState = StageDisplayState.FULL_SCREEN;
				myFullScreen.label = myFSLabelNormal;
			}
		}

		private function setStageNormal():void
		{
			if (root.stage.displayState == "fullScreen") {
				stage.displayState = StageDisplayState.NORMAL;
				myFullScreen.label = myFSLabelFull;
			}
		}

		private function setGlobalStyle():void
		{
            var formatForGlobal:TextFormat = new TextFormat();
            formatForGlobal.font = "宋体";
            formatForGlobal.size = 12;

            var styleName:String = "textFormat";
            var styleValue:Object = formatForGlobal;
            StyleManager.setStyle(styleName, styleValue);

			myShare.useHandCursor = true;
			myDirList.useHandCursor = true;
			myFavorite.useHandCursor = true;
			myNextPic.useHandCursor = true;
			myPrevPic.useHandCursor = true;
			// myPrevPic.label = '上一页';
			myPicList.useHandCursor = true;
			myFullScreen.useHandCursor = true;
		}

		/**
		 * 设置全局XY坐标
		 */
		private function setGlobalXY():void
		{
			// 设置ScrollPane的宽度与高度
			myScrollPane.width  = stage.stageWidth;
			myScrollPane.height = stage.stageHeight - 30;

			var h:int = stage.stageHeight - myFullScreen.height - 3;

			myNextPic.x = (stage.stageWidth / 2); // 设置页列表按钮的X坐标
			// 以下一页为中心的左侧按钮
			myPrevPic.x = myNextPic.x - (myPrevPic.width + myButtonSpace); // 设置上一页按钮的X坐标
			myPicList.x = myPrevPic.x - (myPicList.width + myButtonSpace); // 设置页列表按钮的X坐标
			myDirList.x  = myPicList.x - (myDirList.width + myButtonSpace); // 设置卷（话）列表按钮的X坐标

			// 以下一页为中心的右侧按钮
			myShare.x = myNextPic.x + myNextPic.width + myButtonSpace; // 设置分享按钮的X坐标
			myFavorite.x = myShare.x + myFavorite.width + myButtonSpace; // 设置收藏按钮的X坐标
			myFullScreen.x = myFavorite.x + myFavorite.width + myButtonSpace; // 设置全屏按钮的X坐标

			myFullScreen.y = h; // 设置全屏按钮的Y坐标
			myFavorite.y = h; // 设置收藏按钮的Y坐标
			myPrevPic.y = h; // 设置上一页的Y坐标
			myPicList.y = h; // 设置页列表的Y坐标
			myNextPic.y = h; // 设置下一页的Y坐标
			myShare.y = h; // 设置分享的Y坐标
			myDirList.y = h; // 设置卷(话)列表的Y坐标

			myProgressBar.y = myScrollPane.height / 2 - 30; // 设置进度条Y坐标
			myProgressBar.x = (myScrollPane.width / 2) - (myProgressBar.width / 2); // 设置进度条X坐标

			MessageBox.x = myProgressBar.x - (myProgressBar.width / 2);
			MessageBox.y = myProgressBar.y - 30;
		}

		/**
		 * 获得卷（话）列表路径
		 */
		private function getDirPath():String
		{
			var path:String = xmlPath + comicId + '/dirlist.xml';

			return path;
		}

		private function getDirId():int
		{
			return int(myDirList.getItemAt(dirIndex).id);
		}

		private function getDirName():String
		{
			return (myDirList.getItemAt(dirIndex).label);
		}

		private function getCurrentUrl():String
		{
			return (comicUrl + '?comicid='+comicId+'&dirid='+getDirId()+'&picid='+getPicId());
		}

		/**
		 * 获得图片列表路径
		 */
		private function getPicPath():String
		{
			dirId = getDirId();

			var path:String = xmlPath + comicId + '/' + dirId + '_piclist.xml';

			return path;
		}

		private function getPicId():int
		{
			return int(myPicList.getItemAt(picIndex).id);
		}

		private function getPicUrl(i:int = 0):String
		{
			var imgUrl:String = '';

			if (i == 0) {
				imgUrl = myPicList.value;
			} else if (i <= picNumber) {
				imgUrl = myPicList.getItemAt(i).data;
			}

			return imgUrl;
		}

		private function MessageBoxInit():void
		{
			txt = new TextField();
			txt.autoSize = 'left';
			txt.addEventListener(Event.CHANGE, MessageBoxReSize);
			txt.x = 16;
			txt.y = 33;
			txt.width = 331;
			txt.wordWrap = true;
			MessageBox.addChild(txt);
			OkHander = MessageBoxClose;
            MessageBox.OkBtn.addEventListener(MouseEvent.CLICK, MessageBoxClose);
            MessageBox.CancelBtn.addEventListener(MouseEvent.CLICK, MessageBoxClose);
            MessageBox.visible = false;
		}

		private function MessageBoxShow(msg:String, title:String = '提示信息', timeout:uint = 0, clickHander:Function = null):void
		{
			myProgressBar.visible = false; // 进度条不可见

            if (t1 > 0) {
                clearTimeout(t1);
            }

            MessageBox.x = Math.ceil((stage.stageWidth - MessageBox.width) / 2);
            MessageBox.y = Math.ceil((stage.stageHeight - MessageBox.height) / 2);
            txt.text = msg;
            MessageBox.msgTitle.text = title;
            MessageBox.CancelBtn.visible = clickHander != null;

			MessageBox.OkBtn.removeEventListener(MouseEvent.CLICK, gotoDirList);
			MessageBox.OkBtn.removeEventListener(MouseEvent.CLICK, gotoPrevDir);
			MessageBox.OkBtn.removeEventListener(MouseEvent.CLICK, gotoNextDir);

            if (clickHander != null) {
				OkHander = clickHander;
                MessageBox.OkBtn.addEventListener(MouseEvent.CLICK, clickHander);
            }

            MessageBox.visible = true;
            MessageBox.alpha = 1;
            if (timeout > 0) {
                t1 = setTimeout(MessageBoxClose, timeout);
            }
		}

		private function MessageBoxClose(event:Event = null):void
		{
            if (t1 > 0) {
                clearTimeout(t1);
            }
            if (MessageBox.alpha <= 0) {
                MessageBox.visible = false;
            } else {
				MessageBox.alpha = MessageBox.alpha - 0.1;
				t1 = setTimeout(MessageBoxClose, 30);
			}
		}

		private function MessageBoxReSize(event:Event):void
		{
            var _loc_2:int;
            MessageBox.MsgBoxBg2.width = 320;
            MessageBox.MsgBoxBg1.width = _loc_2;
            _loc_2 = txt.textHeight + 20;
            MessageBox.height = txt.textHeight + 20;
            _loc_2 = _loc_2;
            MessageBox.MsgBoxBg2.height = _loc_2;
            _loc_2 = _loc_2;
            MessageBox.MsgBoxBg1.height = _loc_2;
            txt.height = _loc_2;
            MessageBox.x = (stage.stageWidth - MessageBox.width) / 2;
            MessageBox.y = (stage.stageHeight - MessageBox.height) / 2;
		}

		private function strReplace(str:String, replace:String, replaceWith:String):String
		{
			var sb:String = new String();
			var found:Boolean = false;
			for (var i = 0; i < str.length; i++) {
				if(str.charAt(i) == replace.charAt(0)) {
					found = true;
					for (var j = 0; j < replace.length; j++) {
						if(!(str.charAt(i + j) == replace.charAt(j))) {
							found = false;break;
						}
					}
					if(found) {
						sb += replaceWith;i = i + (replace.length - 1);continue;
					}
				}
				sb += str.charAt(i);
			}

			return sb;
		}

		private function strRemove(str:String, remove:String):String
		{
			return strReplace(str, remove, '');
		}
	}
}